package com.ddm.service.impl.webImpl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ddm.constant.MessageConstant;
import com.ddm.context.BaseContext;
import com.ddm.dto.webDTO.MarketAnDTO;
import com.ddm.dto.webDTO.MarketSpDTO;
import com.ddm.entity.webEntity.Market;
import com.ddm.exception.DataErrorException;
import com.ddm.mapper.MarketMapper;
import com.ddm.result.PageResult;
import com.ddm.service.vxService.UserService;
import com.ddm.service.webService.MarketService;
import com.ddm.utils.BeanCopyUtil;
import com.ddm.vo.webVo.MarketAnVO;
import com.ddm.vo.webVo.MarketSpVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.List;

/**
 * <p>
 *沉香课堂 服务实现类
 * </p>
 *废案
 * @author lwj
 * @since 2025-05-7
 */
@Service
public class MarketServiceImpl extends ServiceImpl<MarketMapper, Market> implements MarketService {

    @Autowired
    private MarketMapper marketMapper;
    @Autowired
    private MarketService mService;
    @Autowired
    private UserService userService;
//    @Override
//    public Result<Market> getById(Long id) {
//        Market market = baseMapper.selectById(id);
//        return market != null ? Result.success(market) : Result.error("记录不存在");
//    }
//
//    @Override
//    public Result<Boolean> saveMarket(Market market) {
//        boolean success = save(market);
//        return success ? Result.success(true) : Result.error("保存失败");
//    }
//
//    @Override
//    public Result<Boolean> updateMarket(Market market) {
//        boolean success = updateById(market);
//        return success ? Result.success(true) : Result.error("更新失败");
//    }
//
//    @Override
//    public Result<Boolean> deleteById(Long id) {
//        boolean success = removeById(id);
//        return success ? Result.success(true) : Result.error("删除失败");
//    }


    /**
     * 分页查询市场分析报告列表,根据用户类型筛选
     * @param mDTO
     * @return
     */
    @Override
    public PageResult getMarketAnListByUserType(MarketAnDTO mDTO) {
//        // 从上下文获取当前用户ID
//        Long userId = BaseContext.getCurrentId();
//
//
//        // 查询用户类型
//        Integer userType = userService.getUserTypeById(userId);
//
        // 构建查询条件
        LambdaQueryWrapper<Market> queryWrapper = new LambdaQueryWrapper<>();
//
//        // 根据用户类型过滤可见文档
//        if (userType == 0) { // 普通用户只能查看普通文档(0)
//            queryWrapper.eq(Market::getAType, 0);
//        } else if (userType == 1 || userType == 2|| userType == 3) {
//            // 管理员，收费用户和VIP用户可以查看所有文档
//            // 无需添加额外条件
//        } else {
//            throw new DataErrorException(MessageConstant.ERROR_DATA);
//        }

        // 通用查询条件
        queryWrapper.orderByAsc(Market::getAPublishDate);

        // 执行分页查询
        Page<Market> page = new Page<>(mDTO.getPage(), mDTO.getPageSize());
        IPage<Market> marketPage = mService.page(page, queryWrapper);

        // 转换结果
        List<MarketAnVO> marketAnVOs = BeanCopyUtil.BeanCopyList(
                marketPage.getRecords(),
                MarketAnVO.class
        );

        return new PageResult(marketPage.getTotal(), marketAnVOs);
    }
//    /**
//     * 分页查询市场分析列表
//     * @param pageQueryDTO
//     * @return
//     */
//    @Override
//    public PageResult getMarketAnList(PageQueryDTO pageQueryDTO) {
//        LambdaQueryWrapper<Market> queryWrapper = new LambdaQueryWrapper<>();
//        Page<Market> classPage = new Page(pageQueryDTO.getPage() , pageQueryDTO.getPageSize());
//        queryWrapper.orderByAsc(Market::getAPublishDate);
//        List<Market> records = mService.page(classPage, queryWrapper).getRecords();
//        long total = classPage.getTotal();
//        List<MarketAnVO> MarketAnVOs = BeanCopyUtil.BeanCopyList(records, MarketAnVO.class);
//        return new PageResult(total,MarketAnVOs);
//    }

    /**
     * 插入市场供求信息列表,根据用户类型筛选，0为普通用户每天可插入一条，1为管理员无限制，2是收费用户每天可插入5条，3是vip用户无限制
     * @param mDTO
     * @return
     */
    @Override
    public String InsertMarketSpListByUserType(MarketSpDTO mDTO) {
        // 从上下文获取当前用户ID
        Long userId = BaseContext.getCurrentId();


        // 查询用户类型
        Integer userType = userService.getUserTypeById(userId);

        // 计算今日日期范围
        LocalDate today = LocalDate.now();
        LocalDateTime startOfDay = today.atStartOfDay();
        LocalDateTime endOfDay = today.atTime(LocalTime.MAX);

        // 检查用户今日已插入的记录数
        LambdaQueryWrapper<Market> countWrapper = new LambdaQueryWrapper<>();
        countWrapper.eq(Market::getUserId, userId)
                .ge(Market::getSdPublishDate, startOfDay)
                .le(Market::getSdPublishDate, endOfDay);

        int todayInsertCount = mService.count(countWrapper);

        // 根据用户类型判断是否允许插入
        if (userType == 0 && todayInsertCount >= 1) {
            throw new DataErrorException(MessageConstant.ERROR_USEROP);
        } else if (userType == 2 && todayInsertCount >= 5) {
            throw new DataErrorException(MessageConstant.ERROR_USEROP);
        }

        Market m = BeanCopyUtil.BeanCopy(mDTO, Market.class);

        // 设置发布日期为当前时间
        m.setSdPublishDate(LocalDateTime.now());

        // 执行插入操作
        boolean success = mService.save(m);
        return success ? "插入成功" : "插入失败";



    }
    /**
     * 查询供求信息
     * @param Dto
     * @return
     */
    @Override
    public PageResult getMarketSpList(MarketSpDTO Dto) {

        LambdaQueryWrapper<Market> queryWrapper = new LambdaQueryWrapper<>();
        Page<Market> mPage = new Page(Dto.getPage() , Dto.getPageSize());
        queryWrapper.orderByAsc(Market::getSdPublishDate);
        List<Market> records = mService.page(mPage, queryWrapper).getRecords();
        long total = mPage.getTotal();
        List<MarketSpVO> ListVos = BeanCopyUtil.BeanCopyList(records, MarketSpVO.class);
        return new PageResult(total,ListVos);
    }
//    @Override
//    public void deleteMarketSpList(List<MarketSpDTO> mDTOS) {
//        // 提取ID列表
//        List<Long> ids = mDTOS.stream()
//                .map(MarketSpDTO::getId)
//                .collect(Collectors.toList());
//
//        // 批量查询验证存在性
//        List<Market> marketList = marketMapper.selectBatchIds(ids);
//
//        // 验证所有记录都存在
//        if (marketList.size() != ids.size()) {
//            throw new DataErrorException(MessageConstant.ERROR_DATA);
//        }
//
//        // 批量删除
//        marketMapper.deleteBatchIds(ids);
//    }
//    @Override
//    public void deleteMarketAnList(List<MarketAnDTO> mDTOS) {
//        // 提取ID列表
//        List<Long> ids = mDTOS.stream()
//                .map(MarketAnDTO::getUserId)
//                .collect(Collectors.toList());
//
//        // 批量查询验证存在性
//        List<Market> marketList = marketMapper.selectBatchIds(ids);
//
//        // 验证所有记录都存在
//        if (marketList.size() != ids.size()) {
//            throw new DataErrorException(MessageConstant.ERROR_DATA);
//        }
//
//        // 批量删除
//        marketMapper.deleteBatchIds(ids);
//    }
}
